package org.jeecg.modules.waybill.service.impl;

import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.LimitSubmit;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.config.wlhy.AmapClient;
import org.jeecg.modules.user.api.JeecgUserApi;
import org.jeecg.modules.user.entity.WlhyCompany;
import org.jeecg.modules.user.entity.WlhyCompanyBothSides;
import org.jeecg.modules.waybill.entity.WlhyWaybillDraft;
import org.jeecg.modules.waybill.mapper.WlhyWaybillDraftMapper;
import org.jeecg.modules.waybill.service.IWlhyWaybillDraftService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static org.jeecg.common.constant.WlhyBizConstant.*;
import static org.jeecg.common.constant.WlhyBizConstant.ROW_STATUS1;

/**
 * @Description: 草稿箱
 * @Author: jeecg-boot
 * @Date:   2024-04-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class WlhyWaybillDraftServiceImpl extends ServiceImpl<WlhyWaybillDraftMapper, WlhyWaybillDraft> implements IWlhyWaybillDraftService {
    @Resource
    JeecgUserApi jeecgUserApi;
    @Resource
    AmapClient amapClient;
    @Override
    @LimitSubmit(key = "saveWaybillDraft:%s:#wlhyWaybillDraft", limit = 2, needAllWait = true)
    public void add(WlhyWaybillDraft wlhyWaybillDraft) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 检测企业状态
        Result<WlhyCompany> companyResult = jeecgUserApi.info();
        if (null == companyResult.getResult() || !COMPANY_AUTH_STATUS2.equals(companyResult.getResult().getAuthStatus())) {
            throw new RuntimeException("当前企业未认证,请认证后再次操作");
        }
        // 检查提货时间和预计送达时间
        Assert.isTrue(wlhyWaybillDraft.getDeliveryTime().getTime() > System.currentTimeMillis(), "提货时间不能早于当前时间");
        Assert.isTrue(wlhyWaybillDraft.getEstArrivalTime().getTime() > System.currentTimeMillis(), "预计送达时间不能早于当前时间");
        // 检查代收款
        if (null != wlhyWaybillDraft.getInvoicingFee() && wlhyWaybillDraft.getInvoicingFee().compareTo(BigDecimal.ZERO) > 0) {

            if (StringUtils.isBlank(wlhyWaybillDraft.getInvoicingPayMode())) {
                throw new RuntimeException("请选择代收款支付方式");
            }
        }

        // 设置当前用户
        wlhyWaybillDraft.setUserId(loginUser.getId());

        // 解析 发货人 经纬度
        try {
            JSONArray shipAddrArray = amapClient.geocodeGeo(wlhyWaybillDraft.getShipperAreaName() + wlhyWaybillDraft.getShipperDetailAddr(), wlhyWaybillDraft.getShipperAreaCode());
            log.info("解析 发货人 经纬度 {}", shipAddrArray);
            if (shipAddrArray.size() == 0) {
                throw new RuntimeException("未解析到发货人地理位置,请写详细一点重新提交表单");
            }
            JSONObject shipAddrObj = JSONObject.parseObject(JSON.toJSONString(shipAddrArray.get(0)));
            wlhyWaybillDraft.setShipperLnglat(shipAddrObj.getString("location"));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        // 解析 收货人 经纬度
        try {
            JSONArray consignerAddrArray = amapClient.geocodeGeo(wlhyWaybillDraft.getConsignerAreaName() + wlhyWaybillDraft.getConsignerDetailAddr(), wlhyWaybillDraft.getConsignerAreaCode());
            log.info("解析 收货人 经纬度 {}", consignerAddrArray);
            if (consignerAddrArray.size() == 0) {
                throw new RuntimeException("未解析到收货人地理位置,请写详细一点重新提交表单");
            }
            JSONObject consignerAddrObj = JSONObject.parseObject(JSON.toJSONString(consignerAddrArray.get(0)));
            wlhyWaybillDraft.setConsignerLnglat(consignerAddrObj.getString("location"));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        // 是否指派司机
        if (1 == wlhyWaybillDraft.getIzAssignDriver()) {
            wlhyWaybillDraft.setOrderTime(new Date());
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverUserId(), "接单用户不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverVehicleNo(), "司机车牌号不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverPhone(), "司机电话不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverName(), "司机姓名不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverBankHolder(), "司机银行开户名不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverBankCardNo(), "司机银行卡号不能为空");
            AssertUtil.assertNotBlank(wlhyWaybillDraft.getDriverBankName(), "司机开户行不能为空");
        }
        wlhyWaybillDraft.setStatus(ROW_STATUS1);

        log.info("保存订单 {}", wlhyWaybillDraft);
        // 此时无需保存 常用双方，因为下单又要保存
        save(wlhyWaybillDraft);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        update(new LambdaUpdateWrapper<WlhyWaybillDraft>().in(WlhyWaybillDraft::getId, ids).set(WlhyWaybillDraft::getStatus, ROW_STATUS0));

    }

    @Override
    public void delete(String id) {
        update(new LambdaUpdateWrapper<WlhyWaybillDraft>().eq(WlhyWaybillDraft::getId, id).set(WlhyWaybillDraft::getStatus, ROW_STATUS0));
    }
}
